
<template>
  <div id="wangeditor">
    <div id="editorElem" ref="editorElem" style="text-align: left"></div>
  </div>
</template>
<script>
import E from "wangeditor";

export default {
  name: "Editor",
  data() {
    return {
      editor: null,
      editorContent: "",
    };
  },
  // catchData是一个类似回调函数，来自父组件，当然也可以自己写一个函数，主要是用来获取富文本编辑器中的html内容用来传递给服务端
  props: ["catchData", "value"], // 接收父组件的方法
  watch: {
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value);
      }
    },
  },
  mounted() {
    this.editor = new E(this.$refs.editorElem);

    // 编辑器的事件，每次改变会获取其html内容
    this.editor.config.uploadImgShowBase64 = false;
    this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024;

    this.editor.config.showLinkImg = false;

    this.editor.config.customUploadImg = async (files, insert) => {
      const res = await this.$uploadImg(files[0]);
      insert(res.data.result.filePath);
    };

    this.editor.config.pasteTextHandle = (content) => {
      //支持粘贴
      return content;
    };

    this.editor.config.onchange = (html) => {
      this.editorContent = html;
      this.catchData(this.editorContent); // 把这个html通过catchData的方法传入父组件
    };
    this.editor.config.menus = [
      // 菜单配置
      "head", // 标题
      "bold", // 粗体
      "fontSize", // 字号
      "fontFamily",
      "lineHeight",
      "italic", // 斜体
      "underline", // 下划线
      "strikeThrough", // 删除线
      "foreColor", // 文字颜色
      "list", // 列表
      "justify", // 对齐方式
      "undo", // 撤销
      "redo", // 重复
      "image",
      "code", // 插入代码
      "backColor", // 背景颜色
    ];
    this.editor.config.colors = [
      "#000000",
      "#eeece0",
      "#1c487f",
      "#4d80bf",
      "#c24f4a",
      "#8baa4a",
      "#7b5ba1",
      "#46acc8",
      "#f9963b",
      "#ffffff",
      "#436CB8",
    ];
    this.editor.config.fontSizes.small.name = "14px";
    this.editor.create(); // 创建富文本实例
    this.editor.txt.html(this.value);
  },
};
</script>
<style lang="less" scoped>
#wangeditor {
  #editorElem ::v-deep .w-e-text-container {
    //设置富文本高度，富文本有个默认300px的高度
    height: 300px !important;
    z-index: 0;
  }
}
/deep/.w-e-text {
  padding: 0;
}
/deep/.w-e-icon-fullscreen {
  color: #fff !important;
  width: 0px !important;
}
</style>